import { HISTORY_KEY } from '@/js/constant'
import { useStore } from 'vuex'
import { save, remove, clear } from '@/js/array-store'

export default function useSearchHistory () {
  const store = useStore()

  function saveSearch (query) {
    const searches = save(query, HISTORY_KEY, (item) => {
      return item === query
    })
    // if (searches.length > 8) {
    //   searches.pop()
    // }
    store.commit('setSearchHistory', searches)
  }

  function deleteSearch (query) {
    const searches = remove(HISTORY_KEY, (item) => {
      return item === query
    })
    store.commit('setSearchHistory', searches)
  }

  function clearSearch () {
    const searches = clear(HISTORY_KEY)
    store.commit('setSearchHistory', searches)
  }
  return {
    saveSearch,
    deleteSearch,
    clearSearch
  }
}
